package com.feel.mall.userservice.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.feel.mall.common.bean.RespBean;
import com.feel.mall.common.bean.User;
import com.feel.mall.common.exception.FeelException;
import com.feel.mall.common.service.UserService;
import com.feel.mall.common.utils.JwtUtil;
import com.feel.mall.common.utils.RedisUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 刘永钦
 * @Description:
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;


    @GetMapping("/captcha")
    public RespBean captcha() {
//        创建验证码对象
        LineCaptcha captcha = new LineCaptcha(120, 32, 4, 10);
//        生成唯一的key -雪花算法生成
        String key = IdUtil.getSnowflakeNextIdStr();
//        将key和验证码存入redis   --超时时间1分钟
        redisUtil.set(key, captcha.getCode(), 60);
//        将验证码转换成Base64编码形式
        String imageBase64 = captcha.getImageBase64();
//        将key和base64编码保存在马匹中
        HashMap<String, Object> map = new HashMap<>();
        map.put("key", key);
        map.put("imageBase64Data", imageBase64);
//        将key和Base64图片返回给前端
        return RespBean.ok("生成验证码成功", map);
    }

    /**
     * 普通用户登录
     */
    @PostMapping("/login")
    public RespBean login(String username, String password, String key, String captchaInput) throws FeelException {
//        判断验证码是否正确
//        从redis中查询验证码判断
        String captcha = (String) redisUtil.get(key);
        if (captcha == null || !captcha.equalsIgnoreCase(captchaInput)) {
            throw new FeelException("验证码错误");
        }
//        登录
        User admin = userService.login(username, password);
//        生成token
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", admin.getId());
        map.put("username", admin.getUsername());
        map.put("roles", "uer");
        String token = JwtUtil.generateJwt(map);
//        将token返回给用户
        return RespBean.ok("登录成功", token);
    }

    /**
     * 用户注册相关接口
     */
    @PostMapping("/registered")
    public RespBean registered(String username, String password, String key, String captchaInput) throws FeelException {
        String captcha = (String) redisUtil.get(key);
        if (captcha == null || !captcha.equalsIgnoreCase(captchaInput)) {
            throw new FeelException("验证码错误");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userService.addInfo(user);
        return RespBean.ok("注册成功" );
    }

    /**
     * 获得全部用户列表(分页查询)
     */
    @GetMapping("/list")
    public RespBean getPageList(User condition, Integer pageNum, Integer pageSize){
        pageNum = pageNum == null || pageNum < 1 ? 1 : pageNum;
        pageSize = pageSize == null || pageSize < 5 ? 5 : pageSize;
        PageInfo<User> pageInfo =(PageInfo<User>) userService.selectByCondition(condition,pageNum,pageSize);
        return RespBean.ok("查询成功", pageInfo);
    }

    /**
     * 通过id查询用户
     */
    @GetMapping("/{id}")
    public RespBean getInfo(@PathVariable("id") Integer id) {
        User user = userService.selectById(id);
        return RespBean.ok("查询成功", user);
    }

    /**
     * 获取登录用户信息
     */
    @GetMapping("/info")
    public RespBean getLoginInfo(@RequestHeader("token") String token) {
        // 解析token
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        //    获得用户id
        Integer id = (Integer) map.get("id");
        User user = userService.selectById(id);

        //     返回
        return RespBean.ok("查询成功", user);
    }
    /**
     * 修改用户信息
     */
    @PutMapping
    public RespBean updateInfo(@RequestBody User user) {
        user.setUsername(null);
        user.setPassword(null);
        // user.setSalt(null);
        userService.updateInfo(user);
        return RespBean.ok("修改成功");
    }

    /**
     * 用户修改密码方法
     */
    @PostMapping("/change/pwd")
    public RespBean changePwd(String password, String newPassword, String newPasswordAgain, @RequestHeader("token") String token) throws FeelException {
        // 解析token
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        //    获得用户id
        Integer userId = (Integer) map.get("id");
        User user = userService.selectById(userId);
        if (user.getStatus() >= 2) {
            throw new FeelException("账户状态错误请重试");
        }

        if (!newPassword.equals(newPasswordAgain)) {
            throw new FeelException("请重新确认密码");
        }

        userService.changePwd(password,newPassword,userId);
        return RespBean.ok("修改成功");
    }

    /**
     * 验证支付密码
     */
    @PostMapping("/verifyPayPassword")
    public RespBean verifyPayPassword(String payPassword, @RequestHeader("token") String token) throws FeelException {
        // 解析token
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        //    获得用户id
        Integer userId = (Integer) map.get("id");

        userService.verifyPayPassword(payPassword,userId);

        return RespBean.ok("验证成功");
    }

    /**
     *  修改支付密码
     */
    @PostMapping("/changePayPassword")
    public RespBean changePayPassword(String payPassword, String newPayPassword, String payPasswordAgain, @RequestHeader("token") String token) throws FeelException {
        // 解析token
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        //    获得用户id
        Integer userId = (Integer) map.get("id");

        if (!newPayPassword.equals(payPasswordAgain)) {
            throw new FeelException("两次密码不同");
        }
        userService.changePayPassword(payPassword,newPayPassword,userId);

        return RespBean.ok("修改成功");
    }

    /**
     *  余额充值
     */
    @PostMapping("/rechargeBalance")
    public RespBean rechargeBalance(BigDecimal money, @RequestHeader("token") String token) throws FeelException {
        // 解析token
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        //    获得用户id
        Integer userId = (Integer) map.get("id");

        userService.rechargeBalance(money,userId);

        return RespBean.ok("充值成功");
    }
}
